package com.oa.hr.skill.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.hr.skill.entity.HrSkill;
import com.oa.hr.skill.entity.HrSkillCategory;
import com.oa.hr.skill.service.SkillCategoryService;
import com.oa.hr.skill.service.SkillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController("oa.hr.skill.hrSkillController")
@RequestMapping(value = "/*/oa/hr/skill/hrSkill")
@Api(tags = {"技能定义表-操作接口"})
public class SkillController {

    static Logger logger = LoggerFactory.getLogger(SkillController.class);

    @Autowired
    private SkillService skillService;
    @Value(value = "${mdp.platform-branch-id:platform-branch-001}")
    String platformBranchId;
    @Autowired
    SkillCategoryService categoryService;

    @ApiOperation(value = "技能定义表-查询列表", notes = " ")
    @ApiEntityParams(HrSkill.class)
    @ApiResponses({@ApiResponse(code = 200, response = HrSkill.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listHrSkill(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        params.put("platformBranchId", this.platformBranchId);
        QueryWrapper<HrSkill> qw = QueryTools.initQueryWrapper(HrSkill.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = skillService.selectListMapByWhere(page, qw, params);

        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @RequestMapping(value = "/getAllHrSkill", method = RequestMethod.GET)
    public Result getAllTag(@RequestParam Map<String, Object> params) {
        List<Map<String, Object>> result = null;


        params.put("platformBranchId", this.platformBranchId);
        result = skillService.getAllHrSkill(params);

        return Result.ok("", "查询成功").setData(result);
    }


    @RequestMapping(value = "/delHrSkillCategory", method = RequestMethod.POST)
    public Result deleteTagCategory(@RequestBody HrSkillCategory tagCategory) {
        Tips tips = new Tips("删除成功");
        HrSkillCategory hrSkillCategoryDb = categoryService.selectOneObject(tagCategory);
        if (hrSkillCategoryDb == null) {
            tips.setErrMsg("category-no-exists", "id", "该分类不存在");
        }
        User user = LoginUtils.getCurrentUserInfo();
        if ("1".equals(hrSkillCategoryDb.getIsPub())) {//如果添加的是公共标签需要检查是否有权限
            if (!platformBranchId.equals(user.getBranchId())) {
                tips.setErrMsg("you-not-platform-branch", "branchId", "只有平台机构账户可以增加公共分类");
            }
        }
        if (tips.isOk()) {
            int i = skillService.deleteHrSkillCategory(tagCategory);
//				if(i>0 && "1".equals(tagCategory.getIsPub())) {//如果添加的是公共标签需要同步更新缓存
//					List<Map<String,Object>> pubTags= this.hrSkillService.selectAllPublicFormDb();
//					this.hrSkillService.putPublicTags(pubTags);
//				}
        }
        return Result.ok().setTips(LangTips.fromTips(tips));
    }

    @ApiOperation(value = "技能定义表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = HrSkill.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addHrSkill(@RequestBody HrSkill hrSkill) {


        HrSkill hrSkillQuery = new HrSkill();
        hrSkillQuery.setCategoryId(hrSkill.getCategoryId());
        hrSkillQuery.setSkillName(hrSkill.getSkillName());
        hrSkillQuery.setIsPub(hrSkill.getIsPub());
        //hrSkillQuery.setId(hrSkill.getId());
        List<HrSkill> skillList = skillService.selectListByWhere(hrSkill);    //列出Tag列表
        if (!CollectionUtils.isEmpty(skillList)) {
            throw new BizException("该标签名字已经存在了，不能添加");
        }
        if (StringUtils.isEmpty(hrSkill.getId())) {
            hrSkill.setId(skillService.createKey("id"));
        } else {
            HrSkill hrSkillQuery2 = new HrSkill(hrSkill.getId());
            if (skillService.countByWhere(hrSkillQuery2) > 0) {
                return Result.error("编号重复，请修改编号再提交");

            }
        }
        if (!StringUtils.hasText(hrSkill.getBranchId())) {
            return Result.error("机构编号不能为空");

        }
        User user = LoginUtils.getCurrentUserInfo();

        if ("1".equals(hrSkill.getIsPub())) {
            if (!platformBranchId.equals(user.getBranchId())) {
                return Result.error("只有平台机构账户可以增加公共标签");
            }
        }
        skillService.insert(hrSkill);

        return Result.ok("add-ok", "添加成功！").setData(hrSkill);
    }

    @ApiOperation(value = "技能定义表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delHrSkill(@RequestBody HrSkill hrSkill) {


        User user = LoginUtils.getCurrentUserInfo();
        HrSkill hrSkillDb = this.skillService.selectOneObject(hrSkill);
        if ("1".equals(hrSkillDb.getIsPub())) {
            if (!platformBranchId.equals(user.getBranchId())) {
                return Result.error("只有平台机构账户可以删除公共标签");
            }
        }
        skillService.deleteByPk(hrSkill);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "技能定义表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = HrSkill.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editHrSkill(@RequestBody HrSkill hrSkill) {
        skillService.updateById(hrSkill);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ApiOperation(value = "技能定义表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = HrSkill.class, props = {}, remark = "技能定义表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = HrSkill.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        skillService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "技能定义表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelHrSkill(@RequestBody List<HrSkill> hrSkills) {
        User user = LoginUtils.getCurrentUserInfo();
        if (hrSkills.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<HrSkill> datasDb = skillService.listByIds(hrSkills.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<HrSkill> can = new ArrayList<>();
        List<HrSkill> no = new ArrayList<>();
        for (HrSkill data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            skillService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "技能定义表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = HrSkill.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(HrSkill hrSkill) {
        HrSkill data = (HrSkill) skillService.getById(hrSkill);
        return Result.ok().setData(data);
    }

}
